<?php

/**
 * The base controller which is used by the Front and the Admin controllers
 */
class MY_Controller extends CI_Controller {
	function __construct()
	{
		parent::__construct();
	}
}
class Front_Controller extends CI_Controller {
	public $data = array();
	function __construct()
	{
		parent::__construct();
	}
}


class Admin_Controller extends MY_Controller {
	public $theme_data = array(
		'layout_main' 	=> 'layout',
		'left' 			=> 'include/leftcp',
		);
	public $heading 			= "";
	public $sub_heading 		= "";
	public $resources 			= "";
	public $url_search 			= '';
	public $permissionCreate = '';
	public $permissionDelete = '';
	public $permissionEdit   = '';
	public $permissionView   = '';
	public $current_permission   = '';
	protected $index_show   	= array();
	public $data   			= array();
	public $data_ajaxtable   = array();

	function __construct()
	{
		parent::__construct();
		$this->load->model("admin_m", 'admin');
		$this->load->model("atheme");
		$this->load->model("roles_m", 'role');
		$this->load->model("permission_m", 'permission');
		$this->load->model("simage");
		$this->load->library('pagination');
		$this->load->library('auth');
		$this->load->library('messages');
		$this->load->library('breadcrumbs');
		$this->load->library('events');
		$this->config->set_item('url_suffix','');
		if(!$this->admin->checkLogin() 
			&& $this->router->fetch_class() !='uindex' 
			&& $this->router->fetch_method() !='login')
		{
			redirect(admin_url());
		}
		$this->url_index = admin_url() . $this->view;
		$this->url_edit = $this->url_index . "/edit/";
		$this->url_delete = $this->url_index . "/delete/";
		$this->url_add = $this->url_index . "/edit/0";
		$this->view_edit = 'edit';
		$this->folder_upload = "images/";
		$_SESSION['RF']["new_subfolder"] = $this->admin->account.'/';
		$this->config->load('site_config', TRUE);
		$this->breadcrumbs->push('Bảng điều khiển', '/');
		$this->load->model("log_admin_activities_m", 'log_activity');

	}


	function nopermission(){
		redirect(admin_url().'nopermission.html');
	}
	
	function edit($edit_id = 0)
	{
		
		$post = $this->input->post();

		if($edit_id >0)
		{
			$this->current_permission = $this->permissionEdit;
		}
		else
		{
			$this->current_permission = $this->permissionCreate;
		}

		// $this->auth->restrict($this->current_permission);
		$this->check_permission($edit_id);

		if ($post && isset($post['edit'])) {
			if($edit_id > 0)
			{
				$this->{$this->model}->update($edit_id, $post['edit']);
				$this->messages->add('Cập nhật thành công.','success');
			}
			else
			{
				$edit_id = $this->{$this->model}->insert($post['edit']);
				$this->messages->add('Thêm mới thành công.','success');
			}
			redirect($this->url_edit . $edit_id);
		}
		
		if(!isset($this->data['edit']))
		{
			$this->data['edit'] = $this->{$this->model}->get($edit_id);
		}
		$this->data['edit_id'] = $edit_id;

		if($edit_id >0 && !$this->data['edit'])
		{
			$this->messages->add('Không tồn tại ID này, vui lòng trở ra kiểm tra lại.','error');
			$this->messages->clear('success');
		}
		
		$this->breadcrumbs->push($this->auth->get_info($this->permissionView)->permission_title, '/'.$this->auth->get_info($this->permissionView)->permission_sidebar_link);
		$this->breadcrumbs->push($this->auth->get_info($this->current_permission)->permission_title, '/');

		$this->theme_data["main"] = $this->view."/".$this->view_edit;
		$this->template->viewAdmin($this->theme_data, $this->data);
	}
	
	function check_permission($editID = 0, $method = ''){
		$this->log_activity->auto_add();
		if(!has_permission($this->current_permission))
		{
			$this->breadcrumbs->push('Lỗi', '/');
			$this->messages->add('Bạn không có quyền vào đây <br> Mã lỗi: '.$this->current_permission,'error');
			$this->theme_data["main"] = "include/no-permission";
			echo $this->template->viewAdmin($this->theme_data, $this->data, TRUE);
			exit(0);
		}
		
		return true;
	}
	
	public function index($page = 0) 
	{
		if($this->current_permission == '')
			$this->current_permission = $this->permissionView;
		$this->check_permission();
		$this->data['header'] = array();
		$this->data['format_cols'] = array();
		$temp = array();
		if($this->index_show)
			foreach($this->index_show as $i=>$r)
			{
				$key = $r['field'];
				$this->data['header'][] = array('name' =>$r['label']);
				$this->data['format_cols'][] = array(
					'aTargets'=>$i,
					'mData' =>$key,
					);
			}
			if(!isset($this->theme_data["main"]) || !$this->theme_data["main"])
				$this->theme_data["main"] = "include/index";

			$this->template->viewAdmin($this->theme_data, $this->data);
	}
		
	function ajax_datatable()
	{
		$result = array();
		$data = array();
		$query_like = array();
		$query_or_like = array();
		$result['data'] =array();
		$model = $this->model;
		$from = $this->input->get('start');
		$limit = $this->input->get('length');
		$columns = $this->input->get('columns');
		$order = $this->input->get('order');
		$search = $this->input->get('search');
		$request_data = $this->input->get('request_data');
		if(isset($this->data_ajaxtable['request_data']) && is_array($this->data_ajaxtable['request_data']))
		{
			$request_data = (array)$request_data;
			$request_data = array_merge($this->data_ajaxtable['request_data'], $request_data);
		}



		foreach($columns as $key =>$column)
		{
		//search by cols
			if(isset($column['search']['value']) && $column['search']['value'] !='')
			{
				$query_like[$column['data']] = $column['search']['value'];
			}
		//search all cols
			if(isset($search['value']) && $search['value'] != '')
			{
				$query_or_like[$column['data']] = $search['value'];
			}
		}
		
		$order_col = $order[0]['column'];
		if(isset($order_col) && isset($columns[$order_col]['data']))
		{
			$this->$model->order_by($columns[$order_col]['data'], $order[0]['dir']);
		}

		if($request_data) {
			if(is_array($request_data))
				$this->$model->where($request_data);
		}
		if($request_data && is_array($request_data) && (count($query_or_like) > 0 || count($query_like) > 0))
			$this->$model->group_start();

		if(count($query_like) > 0)
		{
			$this->$model->like($query_like);
		}
		
		if(count($query_or_like) > 0)
		{
			$this->$model->or_like($query_or_like);
		}
		if($request_data && is_array($request_data) && (count($query_or_like) > 0 || count($query_like) > 0))
			$this->$model->group_end();
		
		$this->$model->limit($limit, $from);
		$data['datas'] = $this->$model->get_many_by();
		$result['sql'] = $this->db->last_query();
		if($data['datas'])
		{
			foreach($data['datas'] as $data)
			{
				$temp = array();
				$arr_rep = array(
					'{url_edit}',
					'{url_index}',
					);
				$arr_rep_val = array(
					$this->url_edit,
					$this->url_index,
					);
				if($this->index_show)
				{
					foreach($this->index_show as $r)
					{
						$key = $r['field'];
						$arr_rep[] = '{'.$key.'}';
						$temp[$key] = $data->{$key};
						$arr_rep_val[] = $temp[$key];
					}
					
					foreach($this->index_show as $r)
					{
						$key = $r['field'];
						if(isset($r['custom_value']))
						{
							$temp[$key] = str_replace($arr_rep,$arr_rep_val,$r['custom_value']);
						}
					}
					
				}
				$result['data'][] =$temp;
			}
		}
		$result['draw'] = intval($_GET['draw']);

		if($request_data) {
			if(is_array($request_data))
				$this->$model->where($request_data);
		}

		if($request_data && is_array($request_data) && (count($query_or_like) > 0 || count($query_like) > 0))
			$this->$model->group_start();

		if(count($query_like) > 0)
		{
			$this->$model->like($query_like);
		}
		if(count($query_or_like) > 0)
		{
			$this->$model->or_like($query_or_like);
		}
		if($request_data && is_array($request_data) && (count($query_or_like) > 0 || count($query_like) > 0))
			$this->$model->group_end();

		

		$result['recordsTotal'] = $this->$model->count_all();
		
		$result['recordsFiltered'] =  $result['recordsTotal'];
		$this->data_ajaxtable['request_data'] = array();
		die(json_encode($result));
	}
		
	function delete($delete_id = 0)
	{
		if($this->current_permission == '')
		$this->current_permission = $this->permissionDelete;
		$this->check_permission();

		$this->{$this->model}->delete($delete_id);
	}
	}
	